package com.uw.uwrpc.core.filter;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.uw.uwrpc.core.api.Filter;
import com.uw.uwrpc.core.api.RpcRequest;
import com.uw.uwrpc.core.api.RpcResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

public class CacheFilter implements Filter {

    Cache<String, RpcResponse> cache = Caffeine.newBuilder()
            // 软引用
            .softValues()
            // 设置最后一次写入或访问后经过固定时间过期
            .expireAfterWrite(60, TimeUnit.SECONDS)
            // 初始的缓存空间大小
            .initialCapacity(100)
            // 缓存的最大条数
            .maximumSize(1000).build();

    @Override
    public boolean before(RpcRequest request, RpcResponse response) {
        RpcResponse cacheResponse = cache.getIfPresent(request.toString());
        if (ObjectUtils.isEmpty(cacheResponse)) {
            return true;
        }

        BeanUtils.copyProperties(cacheResponse, response);
        return false;
    }

    @Override
    public void afterCompletion(RpcRequest request, RpcResponse response, Exception ex) {
        cache.put(request.toString(), response);
    }
}
